import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../../common/models/server_model.dart';
import '../../../common/services/server_service.dart';
import '../../../common/utils/index.dart';

/// 快捷命令
class QuickCommand {
  final String id;
  final String name;
  final String command;
  final String description;
  final IconData icon;
  final Color color;

  QuickCommand({
    required this.id,
    required this.name,
    required this.command,
    required this.description,
    required this.icon,
    required this.color,
  });

  Map<String, dynamic> toJson() => {
    'id': id,
    'name': name,
    'command': command,
    'description': description,
  };

  factory QuickCommand.fromJson(Map<String, dynamic> json) => QuickCommand(
    id: json['id'],
    name: json['name'],
    command: json['command'],
    description: json['description'],
    icon: Icons.terminal,
    color: Colors.blue,
  );
}

class ServerCommandsController extends GetxController {
  final ServerService _serverService = Get.find<ServerService>();
  late final String serverId;

  Rx<ServerModel?> server = Rx<ServerModel?>(null);
  RxList<QuickCommand> commands = <QuickCommand>[].obs;
  RxList<QuickCommand> customCommands = <QuickCommand>[].obs;

  RxBool isExecuting = false.obs;
  RxString commandOutput = ''.obs;
  RxString selectedCommandId = ''.obs;

  // 状态监听订阅
  StreamSubscription<ServerModel>? _stateSubscription;

  @override
  void onInit() {
    super.onInit();
    debugPrint('🎬 ServerCommandsController: onInit');

    serverId = Get.parameters['id'] ?? '';
    debugPrint('   服务器ID: $serverId');

    if (serverId.isEmpty) {
      debugPrint('❌ ServerCommandsController: 服务器 ID 为空');
      LoadingUtil.error('服务器 ID 无效');
      Get.back();
      return;
    }

    _initDefaultCommands();
    _loadCustomCommands();
    _loadServer();
    _listenToServerStateChanges();
  }

  /// 初始化默认命令
  void _initDefaultCommands() {
    commands.value = [
      QuickCommand(
        id: 'uptime',
        name: '系统运行时间',
        command: 'uptime',
        description: '查看系统运行时间和负载',
        icon: Icons.schedule,
        color: Colors.green,
      ),
      QuickCommand(
        id: 'df',
        name: '磁盘使用情况',
        command: 'df -h',
        description: '查看磁盘空间使用情况',
        icon: Icons.storage,
        color: Colors.blue,
      ),
      QuickCommand(
        id: 'free',
        name: '内存使用情况',
        command: 'free -h',
        description: '查看内存使用情况',
        icon: Icons.memory,
        color: Colors.purple,
      ),
      QuickCommand(
        id: 'top',
        name: '进程监控',
        command: 'top -bn1 | head -20',
        description: '查看 CPU 和内存占用前 20 的进程',
        icon: Icons.monitor,
        color: Colors.orange,
      ),
      QuickCommand(
        id: 'netstat',
        name: '网络连接',
        command: 'netstat -tuln',
        description: '查看网络连接和端口',
        icon: Icons.network_check,
        color: Colors.teal,
      ),
      QuickCommand(
        id: 'ps',
        name: '所有进程',
        command: 'ps aux | head -30',
        description: '查看所有运行进程',
        icon: Icons.apps,
        color: Colors.indigo,
      ),
      QuickCommand(
        id: 'docker_ps',
        name: 'Docker 容器',
        command: 'docker ps -a',
        description: '查看所有 Docker 容器',
        icon: Icons.widgets,
        color: Colors.blue,
      ),
      QuickCommand(
        id: 'systemctl',
        name: '系统服务',
        command: 'systemctl list-units --type=service --state=running',
        description: '查看运行中的系统服务',
        icon: Icons.settings_applications,
        color: Colors.deepPurple,
      ),
      QuickCommand(
        id: 'nginx_test',
        name: 'Nginx 配置测试',
        command: 'nginx -t',
        description: '测试 Nginx 配置文件',
        icon: Icons.check_circle,
        color: Colors.green,
      ),
      QuickCommand(
        id: 'clear_cache',
        name: '清理缓存',
        command: 'sync && echo 3 > /proc/sys/vm/drop_caches',
        description: '清理系统缓存（需要 root）',
        icon: Icons.cleaning_services,
        color: Colors.red,
      ),
    ];
  }

  /// 加载自定义命令
  Future<void> _loadCustomCommands() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final key = 'custom_commands_$serverId';
      final jsonStr = prefs.getString(key);
      if (jsonStr != null) {
        final List<dynamic> list = jsonDecode(jsonStr);
        customCommands.value = list.map((e) => QuickCommand.fromJson(e)).toList();
        debugPrint('✅ 加载了 ${customCommands.length} 个自定义命令');
      }
    } catch (e) {
      debugPrint('❌ 加载自定义命令失败: $e');
    }
  }

  /// 保存自定义命令
  Future<void> _saveCustomCommands() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final key = 'custom_commands_$serverId';
      final jsonStr = jsonEncode(customCommands.map((e) => e.toJson()).toList());
      await prefs.setString(key, jsonStr);
      debugPrint('✅ 保存了 ${customCommands.length} 个自定义命令');
    } catch (e) {
      debugPrint('❌ 保存自定义命令失败: $e');
    }
  }

  /// 监听服务器状态变化
  void _listenToServerStateChanges() {
    debugPrint('👂 ServerCommandsController: 开始监听服务器状态变化');
    _stateSubscription = _serverService.watchServer(serverId).listen((updatedServer) {
      debugPrint('📢 ServerCommandsController: 收到服务器状态更新 - ${updatedServer.name}');
      server.value = updatedServer;
    });
  }

  Future<void> _loadServer() async {
    debugPrint('📋 ServerCommandsController: 加载服务器信息 - ID: $serverId');

    server.value = _serverService.getServer(serverId);
    if (server.value == null) {
      debugPrint('❌ ServerCommandsController: 服务器不存在');
      LoadingUtil.error('服务器不存在');
      Get.back();
      return;
    }

    debugPrint('✅ ServerCommandsController: 服务器信息加载成功');
  }

  /// 执行命令
  Future<void> executeCommand(QuickCommand cmd) async {
    if (!_serverService.isConnected(serverId)) {
      LoadingUtil.error('未连接到服务器');
      return;
    }

    isExecuting.value = true;
    commandOutput.value = '';
    selectedCommandId.value = cmd.id;

    try {
      debugPrint('🚀 执行命令: ${cmd.name} - ${cmd.command}');
      final client = _serverService.getClient(serverId);
      if (client == null) {
        throw Exception('未连接到服务器');
      }

      final result = await client.run(cmd.command).timeout(
        const Duration(seconds: 30),
        onTimeout: () {
          throw TimeoutException('命令执行超时');
        },
      );

      final output = utf8.decode(result);
      commandOutput.value = output;

      debugPrint('✅ 命令执行成功');
      // 显示输出对话框
      _showOutputDialog(cmd.name, output);
    } on TimeoutException {
      LoadingUtil.error('命令执行超时');
    } catch (e) {
      debugPrint('❌ 命令执行失败: $e');
      LoadingUtil.error('执行失败: $e');
    } finally {
      isExecuting.value = false;
      selectedCommandId.value = '';
    }
  }

  /// 显示输出对话框
  void _showOutputDialog(String title, String output) {
    Get.dialog(
      AlertDialog(
        title: Text(title, style: const TextStyle(fontSize: 15)),
        content: SizedBox(
          width: double.maxFinite,
          height: 400,
          child: Container(
            decoration: BoxDecoration(
              color: Colors.black87,
              borderRadius: BorderRadius.circular(8),
            ),
            padding: const EdgeInsets.all(12),
            child: SingleChildScrollView(
              child: SelectableText(
                output.isEmpty ? '(无输出)' : output,
                style: const TextStyle(
                  fontSize: 11,
                  fontFamily: 'monospace',
                  color: Colors.greenAccent,
                  height: 1.4,
                ),
              ),
            ),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }

  /// 添加自定义命令
  Future<void> addCustomCommand() async {
    final nameController = TextEditingController();
    final commandController = TextEditingController();
    final descController = TextEditingController();

    final result = await Get.dialog<bool>(
      AlertDialog(
        title: const Text('添加自定义命令', style: TextStyle(fontSize: 15)),
        content: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                controller: nameController,
                decoration: const InputDecoration(
                  labelText: '命令名称',
                  hintText: '例如：查看日志',
                  hintStyle: TextStyle(fontSize: 11),
                ),
                style: const TextStyle(fontSize: 13),
              ),
              const SizedBox(height: 12),
              TextField(
                controller: commandController,
                decoration: const InputDecoration(
                  labelText: '命令',
                  hintText: '例如：tail -f /var/log/nginx/access.log',
                  hintStyle: TextStyle(fontSize: 11),
                ),
                style: const TextStyle(fontSize: 13, fontFamily: 'monospace'),
                maxLines: 2,
              ),
              const SizedBox(height: 12),
              TextField(
                controller: descController,
                decoration: const InputDecoration(
                  labelText: '描述',
                  hintText: '可选',
                  hintStyle: TextStyle(fontSize: 11),
                ),
                style: const TextStyle(fontSize: 13),
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(result: false),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () => Get.back(result: true),
            child: const Text('添加'),
          ),
        ],
      ),
    );

    if (result == true) {
      final name = nameController.text.trim();
      final command = commandController.text.trim();
      final desc = descController.text.trim();

      if (name.isEmpty || command.isEmpty) {
        LoadingUtil.error('请填写命令名称和命令');
        return;
      }

      final newCommand = QuickCommand(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        name: name,
        command: command,
        description: desc.isEmpty ? '自定义命令' : desc,
        icon: Icons.bolt,
        color: Colors.amber,
      );

      customCommands.add(newCommand);
      await _saveCustomCommands();
      LoadingUtil.success('添加成功');
    }
  }

  /// 删除自定义命令
  Future<void> deleteCustomCommand(QuickCommand cmd) async {
    final confirmed = await Get.dialog<bool>(
      AlertDialog(
        title: const Text('确认删除', style: TextStyle(fontSize: 15)),
        content: Text('确定要删除命令 "${cmd.name}" 吗？', style: const TextStyle(fontSize: 12)),
        actions: [
          TextButton(
            onPressed: () => Get.back(result: false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Get.back(result: true),
            style: TextButton.styleFrom(foregroundColor: Colors.red),
            child: const Text('删除'),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      customCommands.removeWhere((c) => c.id == cmd.id);
      await _saveCustomCommands();
      LoadingUtil.success('删除成功');
    }
  }

  @override
  void onClose() {
    debugPrint('🔚 ServerCommandsController: onClose');
    _stateSubscription?.cancel();
    super.onClose();
  }
}

